#include "QCVInterface.h"

QCVInterface::QCVInterface()
{  
  create_widgets();
  create_actions();
  connect_signals2slots();

	setAcceptDrops(true);
}
////////////////////////////////////////////////////////////////////////////////
bool QCVInterface::add_module(QString filename)
{
	pQCVModuleHandler p=new QCVModuleHandler(filename);
	
	if(p->isLoaded())
	{
		p->setAttribute(Qt::WA_DeleteOnClose);
		mdiArea->addSubWindow(p);
		p->show();

		connect(p, SIGNAL(move()),mdiArea->viewport(), SLOT(update()));
		connect(p, SIGNAL(move()),mdiArea, SLOT(update()));  
		connect(p,SIGNAL(isClosing(QCVModuleHandler*)),this,SLOT(s_removeLinks(QCVModuleHandler*)));
	}
	
	return p->isLoaded();
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::add_module()
{
	QStringList filenames=QFileDialog::getOpenFileNames(this,tr("Ouvrir des Modules"),tr("modules"),tr("Tous (*.so *.dll);;Linux (*.so);;Windows (*.dll)"));	

  for(int i=0;i<filenames.size();i++)
  {
    add_module(filenames[i]);
  } 
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::remove_module()
{
  //on récupere le module actif
  QMdiSubWindow * p=mdiArea->activeSubWindow();
  
  //on le supprime
  if(p)
  {
    p->close();
    mdiArea->remove_links((pQCVModuleHandler)p);
  }
}
////////////////////////////////////////////////////////////////////////////////    
void QCVInterface::create_widgets()
{
	mdiArea= new QMyMdiArea();
	//tb_modules=new QToolBar();
	//addToolBar(Qt::LeftToolBarArea,tb_modules);
	this->setCentralWidget(mdiArea);
	menu_file = menuBar()->addMenu("Fichier");
	menu_modules = menuBar()->addMenu("Modules"); 
	menu_view = menuBar()->addMenu("Vue"); 
	menu_help = menuBar()->addMenu("Aide");  
}
////////////////////////////////////////////////////////////////////////////////    
void QCVInterface::create_actions()
{
	a_reload_module=new QAction("Recharger",this);
	a_reload_module->setShortcut(tr("Ctrl+R"));  
	a_add_module=new QAction("Ajouter",this);
	a_add_module->setShortcut(tr("Ctrl+M"));
	a_remove_module=new QAction("Supprimer",this);
	a_remove_module->setShortcut(tr("Esc"));
	a_cascade_modules=new QAction("Cascade",this);
	a_cascade_modules->setShortcut(tr("Alt+C"));
	a_tile_modules=new QAction("Arrange",this);
	a_tile_modules->setShortcut(tr("Alt+A"));
	a_remove_selected_links=new QAction("Supprimer les liens",this);
	a_remove_selected_links->setShortcut(tr("Del"));
	a_open_project=new QAction("Ouvrir",this);
	a_open_project->setShortcut(tr("Ctrl+O"));
	a_save_project=new QAction("Sauver",this);
	a_save_project->setShortcut(tr("Ctrl+S"));
	a_close_project=new QAction("Fermer",this);
	a_close_project->setShortcut(tr("Ctrl+C"));
	a_quit=new QAction("Quitter",this);
	a_quit->setShortcut(tr("Ctrl+Q"));

	a_refresh=new QAction(tr("Rafraichir la vue"),this);
	a_refresh->setShortcut(tr("F5"));

	a_about=new QAction(trUtf8("A propo de Clémentine..."),this);	
	a_hints=new QAction(trUtf8("A Savoir..."),this);
	a_about_qt=new QAction(trUtf8("A propo Qt..."),this);

	menu_modules->addAction(a_add_module);
	menu_modules->addAction(a_remove_module);
	menu_modules->addAction(a_remove_selected_links);
	menu_modules->addAction(a_reload_module);
				  
	menu_file->addAction(a_open_project);
	menu_file->addAction(a_save_project);
	menu_file->addAction(a_close_project);
	menu_file->addAction(a_quit);

	menu_view->addAction(a_cascade_modules);
	menu_view->addAction(a_tile_modules);
	menu_view->addAction(a_refresh);

	menu_help->addAction(a_about);
	menu_help->addAction(a_about_qt);
	menu_help->addAction(a_hints);
}
////////////////////////////////////////////////////////////////////////////////    
void QCVInterface::connect_signals2slots()
{
	connect(a_add_module,SIGNAL(triggered()),this,SLOT(add_module()));
	connect(a_remove_module,SIGNAL(triggered()),this,SLOT(remove_module()));
	connect(a_cascade_modules,SIGNAL(triggered()),mdiArea,SLOT(cascadeSubWindows()));
	connect(a_tile_modules,SIGNAL(triggered()),mdiArea,SLOT(tileSubWindows()));
	connect(a_quit,SIGNAL(triggered()),this,SLOT(close()));
	connect(a_open_project,SIGNAL(triggered()),this,SLOT(open_project()));
	connect(a_save_project,SIGNAL(triggered()),this,SLOT(save_project()));
	connect(a_close_project,SIGNAL(triggered()),this,SLOT(close_project()));
	connect(a_about,SIGNAL(triggered()),this,SLOT(about()));
	connect(a_about_qt,SIGNAL(triggered()),this,SLOT(about_qt()));
	connect(a_remove_selected_links,SIGNAL(triggered()),mdiArea,SLOT(remove_selected_links()));
	connect(a_reload_module,SIGNAL(triggered()),this,SLOT(s_reload_module()));
	connect(a_refresh,SIGNAL(triggered()),this,SLOT(s_updateMdi()));
	connect(a_hints,SIGNAL(triggered()),this,SLOT(forceHints()));
}
////////////////////////////////////////////////////////////////////////////////    
void QCVInterface::open_project()
{
  QString filename=QFileDialog::getOpenFileName(this,tr("Sauver le projet"),tr("projets"),tr("Projet clementine (*.cpro)"));
  if(!filename.isEmpty())
  {
    QFile file(filename);
    if (file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
      close_project();
      QTextStream in(&file);
      
      int nblines=0;int cline=0;
      nblines=in.readLine().toInt();
      cline=0;
      
      while((cline++)<nblines) 
      {
        int x=0,y=0,w=0,h=0;
        QStringList line_splited=in.readLine().split(";",QString::SkipEmptyParts);
        if(line_splited.size()==5)
        {
          if(!add_module(line_splited[0]))return;
          x=line_splited[1].toInt();
          y=line_splited[2].toInt();
          w=line_splited[3].toInt();
          h=line_splited[4].toInt();
          
          mdiArea->subWindowList()[mdiArea->subWindowList().size()-1]->move(x,y);
          mdiArea->subWindowList()[mdiArea->subWindowList().size()-1]->resize(w,h);

			if(!((pQCVModuleHandler)(mdiArea->subWindowList()[mdiArea->subWindowList().size()-1]))->setParams(in.readLine()))
			{
				QMessageBox::critical(this,"Erreur","Fichier corrompu!");
				return;
			}    
        }
        else
        {
          QMessageBox::critical(this,"Erreur","Fichier corrompu!");
          return;
        }       
      }
      
      nblines=in.readLine().toInt();
      cline=0;
      while((cline++)<nblines) 
      {
        QStringList line_splited=in.readLine().split(";",QString::SkipEmptyParts);
        if(line_splited.size()==3)
        {
           mdiArea->create_link(line_splited[0].toInt(),line_splited[1].toInt(),line_splited[2].toInt());
        }
        else
        {
          QMessageBox::critical(this,"Erreur","Fichier corrompu!");
          return;
        }
      }
                   
      file.close();
    }
    else
    {
      QMessageBox::information(this,"Erreur","Impossible d'ouvrir/creer le fichier");
    }
  }
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::save_project()
{
  QString filename=QFileDialog::getSaveFileName(this,tr("Sauver le projet"),tr("projets"),tr("Projet clementine (*.cpro)"));
  if(!filename.isEmpty())
  {
    QFile file(filename);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
      QTextStream out(&file);
      out<<mdiArea->subWindowList().size()<<"\n";
      for(int i=0;i<mdiArea->subWindowList().size();i++)
      {
				QDir dir(QDir::currentPath());        
				out<<dir.relativeFilePath(((pQCVModuleHandler)mdiArea->subWindowList()[i])->getFilename())<<";";        
        out<<mdiArea->subWindowList()[i]->x()<<";";
        out<<mdiArea->subWindowList()[i]->y()<<";";
        out<<mdiArea->subWindowList()[i]->width()<<";";
        out<<mdiArea->subWindowList()[i]->height()<<";";
        out<<"\n";
				out<<((pQCVModuleHandler)mdiArea->subWindowList()[i])->getParams();
				out<<"\n";
      }
      
      QList<Link> links_liste=mdiArea->getLinks();
      out<<links_liste.size()<<"\n";
      for(int i=0;i<links_liste.size();i++)
      { 
        out<<mdiArea->getId((pQCVModuleHandler)(links_liste[i].mod1))<<";";
        out<<mdiArea->getId((pQCVModuleHandler)(links_liste[i].mod2))<<";";
        out<<links_liste[i].idInput<<";";  
        out<<"\n";
      }
      
      file.close();
    }
    else
    {
      QMessageBox::information(this,"Erreur","Impossible d'ouvrir/creer le fichier");
    }
  }
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::close_project()
{    
  for(int i=0;i<mdiArea->subWindowList().size();)
  {
    QMdiSubWindow * p=mdiArea->subWindowList()[i];
    if(p)
    {
      p->close();
      mdiArea->remove_links((pQCVModuleHandler)p); 
    }  
  }  
}

void QCVInterface::closeEvent(QCloseEvent * event)
{
  close_project();
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::about_qt()
{
	QMessageBox::aboutQt(this,tr("A propo de Qt"));
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::about()
{
	QFile file("config/about.txt");
	if(file.open(QIODevice::ReadOnly | QIODevice::Text))
  {
		QMessageBox::information(this,trUtf8("Clémentine"),trUtf8(file.readAll()));
		file.close();
	}
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::s_removeLinks(QCVModuleHandler* pthis)
{
	mdiArea->remove_links(pthis); 
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::s_reload_module()
{
	//on récupere le module actif
  QMdiSubWindow * m=mdiArea->activeSubWindow();

	if(m)
	{
		((pQCVModuleHandler)m)->reload();
	}	
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::s_updateMdi()
{
	mdiArea->viewport()->update();
	mdiArea->update();
	this->update();
}

////////////////////////////////////////////////////////////////////////////////
void QCVInterface::dropEvent ( QDropEvent * event )
{
	for(int i=0;i<event->mimeData()->urls().size();i++)
	{
		#ifdef UNIX		
			add_module(event->mimeData()->urls()[i].path());
		#else
			add_module(event->mimeData()->urls()[i].path().remove(0,1));
		#endif
	}
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::dragEnterEvent(QDragEnterEvent *event)
{
   if (event->mimeData()->hasUrls())
	 {
       event->acceptProposedAction();
	 }
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::hints()
{
	QAdwiceDialog * diag=new QAdwiceDialog(windowIcon().pixmap(120),QString("config/adwice.txt"),this);
	if(diag->isAsked())
	{
		diag->show();
	}
}
////////////////////////////////////////////////////////////////////////////////
void QCVInterface::forceHints()
{
	QAdwiceDialog * diag=new QAdwiceDialog(windowIcon().pixmap(120),QString("config/adwice.txt"),this);
	diag->show();
}
